<template>
  <div>
    <el-dialog class="positionDialog" :title="ruleForm.id ? '修改仓储' : '新增仓储'" :visible="showDialog" width="90%"
      :before-close="handleClose" :modal="false" :close-on-click-modal="false">
      <div class="content">
        <el-divider>{{ ruleForm.id ? '修改仓储' : '新增仓储' }}</el-divider>
        <div class="inside-box">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <div class="form-item">
              <div class="title fir-title">
                <svg-icon class="svg-icon" icon-class="infoAdd" />
                <span>仓储信息</span>
              </div>
              <div class="form">
                <el-form-item label="农场名称" prop="farmCode">
                  <el-select style="width: 100%;" @change="changeFram" :disabled="$status!=0" v-model="ruleForm.farmCode" filterable
                    placeholder="请选择农场名称或输入关键词">
                    <el-option v-for="item in carList.farmList" :key="item.value" :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="生产队名称" prop="teamCode">
                  <el-select style="width: 100%;" v-model="ruleForm.teamCode" :disabled="$status==2" filterable placeholder="请选择生产队名称或输入关键词">
                    <el-option v-for="item in carList.teamList" :key="item.value" :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="仓库类型" prop="warehouseType">
                  <el-select style="width: 100%;" v-model="ruleForm.warehouseType" filterable
                    placeholder="请选择仓库类型或输入关键词">
                    <el-option v-for="item in carList.storageList" :key="item.value" :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="仓号" prop="warehouseNumber">
                  <el-input v-model="ruleForm.warehouseNumber" placeholder="请输入仓号"></el-input>
                </el-form-item>
                <el-form-item label="额定仓容(公斤)" prop="rated">
                  <el-input v-model="ruleForm.rated" placeholder="请输入额定仓容"></el-input>
                </el-form-item>
                <el-form-item label="当前仓量(公斤)" prop="">
                  <el-input v-model="ruleForm.current" disabled placeholder="请输入当前仓量"></el-input>
                </el-form-item>
              </div>
            </div>
            <div class="form-item">
              <div class="title fir-title">
                <svg-icon class="svg-icon" icon-class="infoAdd" />
                <span>负责人信息</span>
              </div>
              <div class="form">
                <el-form-item label="姓名" prop="personName">
                  <el-input v-model="ruleForm.personName" placeholder="请输入姓名"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="ruleForm.phone" placeholder="请输入手机号"></el-input>
                </el-form-item>
              </div>
            </div>
          </el-form>
          <div class="table-box">
            <div class="arrowheadLeft" @click="activeBox = !activeBox">
              < </div>
                <div class="arrowheadRight" @click="activeBox = !activeBox">
                  >
                </div>
                <div class="table" v-show="activeBox">
                  <div class="button-box">
                    <el-button class="addButton" type="primary" icon="el-icon-plus" size="mini"
                      style="margin-right: 10px;" @click="handleShowAddDialog">新增</el-button>
                    <el-popconfirm confirm-button-text='确定' cancel-button-text='取消' icon="el-icon-info" icon-color="red"
                      title="确定删除所勾选的数据吗？" @confirm="handleDel">
                      <el-button slot="reference" type="danger" plain icon="el-icon-delete" size="mini">删除</el-button>
                    </el-popconfirm>
                    <el-button type="info" plain icon="el-icon-upload2" size="mini" style="margin-left: 10px;"
                      @click="handleSelectAll">全选</el-button>
                  </div>
                  <TableCom ref="tableCom" :tableHead="tableHead" :tableData="tableData" :tableOperate="tableOperate"
                    :delList.sync="delList">
                  </TableCom>
                </div>
                <div class="img" v-show="!activeBox">
                  暂无照片
                </div>

            </div>
          </div>
        </div>
        <el-dialog
          width="30%"
          title="提示"
          style="overflow: auto;"
          :visible.sync="innerVisible"
          append-to-body>
          <div style="height: 50px;">如直接返回，页面所填信息会丢失，请点击取消按钮返回原界面进行确认保存</div>
          <div class="dialog-footer">
            <el-button class="submit" @click="handleClose">确 认</el-button>
          <el-button class="back" @click="innerVisible=false">取 消</el-button>
        </div>

        </el-dialog>
        <div class="dialog-footer">
          <el-button class="submit" @click="handleSubmit">确 认</el-button>
          <el-button class="back" @click="innerVisible=true">返 回</el-button>
        </div>
    </el-dialog>
    <InsidePopu2 ref="addPopu" :setTableData="setTableData" @getTable="getTAbelList" :showDialog.sync="showInsideDialog"></InsidePopu2>
  </div>
</template>

<script>
import rules from '@/utils/rules'
import { getUserKey } from '@/utils/auth'
import { formatDate } from '@/utils/methods'
import { warehouseAddApi, warehouseupdateApi,stampGetApiAA,stampDeleteApi } from '@/api/cageMange'
import { selectApi } from '@/api/select'
import TableCom from '@/components/TableCom'
import InsidePopu2 from './InsidePopu2.vue'
export default {
  props: ['showDialog'],
  components: {
    TableCom,
    InsidePopu2
  },
  data() {
    return {
      activeBox: true,
      ruleForm: {},
      innerVisible:false,
      // warehouseType warehouseNumber rated
      rules: {
        farmCode: [
          { required: true, message: '请选择农场', trigger: 'change' },
        ],
        teamCode: [
          { required: true, message: '请选择生产队', trigger: 'change' },
        ],
        personName: [
          { required: true, message: '请输入姓名', trigger: 'change' },
        ],
        warehouseType: [
          { required: true, message: '请选择仓库类型', trigger: 'change' },
        ],
        warehouseNumber: [
          { required: true, message: '请输入仓号', trigger: 'change' },
        ],
        rated: [
          { required: true, message: '请输入额定仓容', trigger: 'change' },
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'change' },
        ],
      },
      carList: {
        storageList: [],
        farmList: [],
        teamList: [],
      },
      tableHead: [{
        title: '垛号',
        prop: 'stampId'
      }, {
        title: '粮食种类',
        prop: 'cropType'
      }, {
        title: '粮食品质',
        prop: 'cropQuality'
      }, {
        title: '批次',
        prop: 'batch'
      }, {
        title: '实重(公斤)',
        prop: 'solid'
      }, {
        title: '初始仓量(公斤)',
        prop: 'initial'
      }],
      tableData: [],
      updataType: "0",
      tableOperate: [{
        title: '修改',
        handle: (row) => {
          this.$refs.addPopu.ruleForm = { ...row }
          this.showInsideDialog = true
        },
        flag: (row) => {
          return true
        }
      }],
      delList: [],
      showInsideDialog: false,
    };
  },
  methods: {
    setTableData(data, type) {
      if (type == 'add') {
        if (this.tableData.findIndex((item) => {
          return item.stampId == data.stampId
        }) != -1) {
          this.$message({
            type: 'warning',
            message: '该垛号已存在，请重新输入'
          });
          return;
        }
        // if (this.tableData.findIndex((item) => {
        //   return item.cropType == data.cropType && item.cropQuality == data.cropQuality
        // }) != -1) {
        //   this.$message({
        //     type: 'warning',
        //     message: '该作物类型已存在该品质，请重新输入'
        //   });
        //   return;
        // }
        this.tableData.push({ ...data, id: new Date().getTime() })
        this.$refs.addPopu.handleClose()
      } else {
        // const aa = this.tableData.findIndex((item) => {
        //   return item.id == data.id
        // })
        // this.tableData.splice(aa, 1, data)
        // this.$refs.addPopu.handleClose()
        const i = this.tableData.findIndex(item => item.id == data.id)
        const list = this.tableData.filter(item => item.id != data.id)
        const n = list.findIndex(item => item.cropType == data.cropType)
        if (n > -1) {
          Message({
            message: '该作物已存在',
            type: 'error',
            duration: 5 * 1000
          })
          return
        } else {
          let obj = {
            id: data.id,
            farmCode:this.$farmCode,
            teamCode:this.$teamCode,
            stampId: data.stampId,
            cropQuality: data.cropQuality,
            cropType: data.cropType,
            solid:data.solid,
            initial:data.initial,
            batch:data.batch
          }
          this.tableData.splice(i, 1, { ...obj })
        }
      }
      this.ruleForm = {
        ...this.ruleForm,
        current: setNum(this.tableData)
      }
      function setNum(arr) {
        let num = 0
        arr.forEach((item) => {
          num = num * 1 + item.solid * 1
        })
        return num
      }

    },
    changeFram(e) {
      selectApi({ type: e }).then((res) => {
        this.carList.teamList = res.data.dictItemList;
      })
    },
    handleClose() {
      this.$emit('update:showDialog', false)
      this.innerVisible = false
      this.ruleForm = {
        carName: '',
        carType: '',
        createUser: '',
        createTime: '',
        current: 0
      }
      this.tableData=[]
      this.$refs.ruleForm.resetFields();
    },
    handleSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          // stamp
          this.ruleForm.stamp = this.tableData.map((item) => {
            delete item.id
            return item;
          })
          this.ruleForm={
            ...this.ruleForm,
          }
          if (this.ruleForm.id) {
            await warehouseupdateApi(this.ruleForm).then((res)=>{
              this.$emit('update:showDialog', false)
              this.ruleForm = {
                carName: '',
                carType: '',
                createUser: '',
                createTime: '',
                current: 0
              }
            })
          } else {
            if(!this.ruleForm.stamp.lenght){
              this.ruleForm = {
                ...this.ruleForm,
                current: 0
              }
            }
            await warehouseAddApi(this.ruleForm).then((res)=>{
              this.$emit('update:showDialog', false)
              this.ruleForm = {
                carName: '',
                carType: '',
                createUser: '',
                createTime: '',
                current: 0
              }
            })

          }

          this.$emit('handleRefresh')
          this.handleClose()
        } else {
          return false;
        }
      });
    },
    // 获取填报人时间
    handleGetInfo() {
      this.ruleForm.createUser = getUserKey() || 'nkjtcyf'
      this.ruleForm.createTime = formatDate(new Date())
    },
    handleShowAddDialog() {
      this.$refs.addPopu.ruleForm.warehouseId=this.ruleForm.id
      this.showInsideDialog = true
    },

    // 全选取消全选
    handleSelectAll() {
      this.$refs.tableCom.toggleSelection(this.tableData)
    },
    // 删除
    async handleDel() {
      this.delList.forEach((item, index) => {
        this.tableData.forEach((v, i) => {
          if (item == v.id) {
            this.tableData.splice(i, 1)
          }
        })
      })
      this.ruleForm = {
        ...this.ruleForm,
        current: setNum(this.tableData)
      }
      function setNum(arr) {
        let num = 0
        arr.forEach((item) => {
          num = num * 1 + item.solid * 1
        })
        return num
      }
      // stampDeleteApi(this.delList)
      // this.getTAbelList()
      // await carDelApi(this.delList)
      // this.getList()
    },
    getTAbelList(){
      stampGetApiAA({ warehouseId: this.ruleForm.id }).then((res) => {
        this.tableData = res.data
      })
    }
  },
  mounted() {
  }
}
</script>

<style lang='scss' scoped>
.inside-box {
  display: flex;
  justify-content: space-between;
}

.table-box {
  width: 68%;
  border-radius: 15px;
  box-shadow: 0 0 5px #ccc;
  padding: 2%;
  position: relative;

  .arrowheadLeft {
    position: absolute;
    top: 40%;
    left: 5px;
    height: 36px;
    width: 36px;
    border-radius: 18px;
    font-size: 20px;
    line-height: 36px;
    background-color: #eee;
    text-align: center;
    color: #fff;
    transition: 1s;
    cursor: pointer;
  }

  .arrowheadLeft:hover {
    background-color: #ccc;
  }

  .arrowheadRight {
    position: absolute;
    top: 40%;
    right: 5px;
    height: 36px;
    width: 36px;
    border-radius: 18px;
    font-size: 20px;
    line-height: 36px;
    background-color: #eee;
    text-align: center;
    color: #fff;
    transition: 1s;
    cursor: pointer;
  }

  .arrowheadRight:hover {
    background-color: #ccc;
  }
}

.el-form {
  width: 30%;
  height: 580px;
  overflow-y: auto;

  .form-item {
    width: 90%;
  }
}

.fir-title {
  margin-top: 0 !important;
}

.el-divider {
  margin-bottom: 40px !important;
}

.el-divider--horizontal {
  height: 3px;
  background-color: #16a085;
}

::v-deep .el-divider__text {
  color: #16a085;
  font-size: 38px;
  font-weight: 700;
}

.demo-ruleForm {
  width: 400px;
}

::v-deep .el-input {
  height: 36px;
}

::v-deep .el-select {
  height: 36px;
}

::v-deep .el-input__icon {
  line-height: 36px;
}

::v-deep .el-input__inner {
  height: 36px;
}
</style>
